ProductAddPortlet = Class.extend({
	init: function()	{
		this.name = "ProductAddPortlet";
	},
	
	onBegin: function()	{
		this.registerObserver();
	},
	
	onEnd: function()	{
		this.unregisterObserver();
	},
	
	run: function()	{
		var obj = this;
		obj.model = {};
		obj.model.root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
		this.getPortletPlaceholder().paintCanvas(this.render());
		
		obj.requestForEffectiveResource('ImageUploader').submit(function() {
			var fr = $('#avatar-upload-frame');
			$(fr).one('load', function() {
				var response = fr.contents().find('body').html();
		    	var ret = $.parseJSON(response);
		    	if (ret.result == "error")	{
		    		alert('Chưa thể cập nhật ảnh!');
		    	} else {
		    		alert('Thêm thành công');
					obj.requestForEffectiveResource('Name').val('');
					obj.requestForEffectiveResource('Description').val('');
					subject.notifyEvent('ProductsChanged');
		    	}
			});
		});
		
		this.onAjax('categories', 'load-leaf-categories', {}, 'GET', {
			'onSuccess': function(ret)	{
				obj.requestForEffectiveResource('CategoryContainer').html(obj.renderView('CategoryTmpl', {cats: ret}));
			}
		});
		
		//TEXT EDITOR TRANSFORMATION
		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent('RenderTextEditor', {id: 'ProductAddPortlet-Description', content: ''});
	},
	
	onProductAddSubmit: function()	{
		var name=this.requestForEffectiveResource('Name').val();
		if (name.trim() == '')	{
			alert('Bạn chưa nhập tên sản phẩm');
			return;
		}
		
		//RETRIEVE TEXT EDITOR CONTENT
		var subject = SingletonFactory.getInstance(Subject);
		var obj = this;
		subject.notifyEvent('RetrieveTextEditorContent', {id: 'ProductAddPortlet-Description', callback: function(description) {
			var cid=obj.requestForEffectiveResource('Category').val();
			var is_new=obj.requestForEffectiveResource('New').is(':checked');
			var is_featured=obj.requestForEffectiveResource('Featured').is(':checked');
			is_new = is_new == true ? 1 : 0;
			is_featured = is_featured == true ? 1 : 0;
			
			var subject = SingletonFactory.getInstance(Subject);
			obj.onAjax('admin', 'add-new-product', {name: name, description: description, category_id: cid, is_new: is_new, is_featured: is_featured}, 'POST', {
				'onSuccess': function(ret)	{
					obj.requestForEffectiveResource('ID').val(ret);
					obj.requestForEffectiveResource('ImageUploader').submit();
				}
			});
		}});
	}
}).implement(PortletInterface).implement(RenderInterface).implement(AjaxInterface).implement(ObserverInterface);